<template>
  <div>
    <el-card shadow="never" class="dashboard-card">
      <template #header>
        <div class="card-header">
          <el-icon>
            <List />
          </el-icon>
          <span>课程管理</span>
          <div class="header-actions">
            <el-input v-model="searchCourseName" placeholder="搜索课程名称" clearable class="search-input"
              @input="filterCourses">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <el-button type="primary" size="small" @click="openAddDialog" class="gradient-blue-toggle-button">新建课程</el-button>
            <el-button size="small" class="gradient-blue-toggle-button" @click="toggleView">
              {{ isCardView ? '切换为列表' : '切换为卡片' }}
            </el-button>
          </div>
        </div>
      </template>

      <el-row :gutter="20" class="chart-section">
        <el-col :span="8">
          <el-card class="chart-card">
            <h3>课程类型分布</h3>
            <div ref="courseTypeDistributionChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <h3>课程进度分布</h3>
            <div ref="courseProgressDistributionChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="chart-card">
            <h3>学分分布</h3>
            <div ref="creditDistributionChart" style="width: 100%; height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <div v-loading="loading">
        <template v-if="isCardView">
          <el-row :gutter="10" class="course-card-grid">
            <template v-if="filteredCourses.length > 0">
              <el-col :xs="12" :sm="8" :md="6" :lg="3" v-for="course in filteredCourses" :key="course.id">
                <el-card class="course-card">
                  <div class="course-card-content">
                    <h4 class="course-card-title" :title="course.name">{{ course.name }}</h4>
                    <p class="course-card-info">
                      <span class="info-label">类型:</span> {{ typeMap[course.courseType] || course.courseType }}
                    </p>
                    <p class="course-card-info">
                      <span class="info-label">教师:</span> {{ teacherName(course.teacherId) }}
                    </p>
                    <p class="course-card-info">
                      <span class="info-label">学分:</span> {{ course.credit }}
                    </p>
                    <p class="course-card-info">
                      <span class="info-label">进度:</span> {{ parseProgress(course.startDate, course.endDate) }}
                    </p>
                  </div>
                  <div class="course-card-actions">
                    <el-button size="small" @click="openEditDialog(course)" class="action-button">
                      编辑
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteCourse(course)"
                      class="action-button light-red-button">
                      删除
                    </el-button>
                  </div>
                </el-card>
              </el-col>
            </template>
            <div v-else class="empty-courses">
              <el-empty description="暂无课程，请新建或调整搜索条件"></el-empty>
            </div>
          </el-row>
        </template>

        <template v-else>
          <el-table :data="filteredCourses" style="width: 100%" stripe border class="rounded-lg overflow-hidden shadow-sm">
            <el-table-column prop="name" label="课程名称" min-width="200" show-overflow-tooltip />
            <el-table-column prop="courseType" label="类型">
              <template #default="scope">
                {{ typeMap[scope.row.courseType] || scope.row.courseType }}
              </template>
            </el-table-column>
            <el-table-column prop="teacherId" label="授课教师">
              <template #default="scope">
                {{ teacherName(scope.row.teacherId) }}
              </template>
            </el-table-column>
            <el-table-column prop="credit" label="学分" />
            <el-table-column prop="progress" label="进度">
              <template #default="scope">
                {{ parseProgress(scope.row.startDate, scope.row.endDate) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" align="center">
              <template #default="scope">
                <el-button size="small" @click="openEditDialog(scope.row)">
                  编辑
                </el-button>
                <el-button size="small" type="danger" @click="deleteCourse(scope.row)" class="light-red-button">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="editMode ? '编辑课程' : '新建课程'" width="50%" :before-close="handleClose">
      <el-form :model="form" ref="formRef" :rules="rules" label-width="100px">
        <el-form-item label="课程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item label="课程描述" prop="description">
          <el-input type="textarea" v-model="form.description" placeholder="请输入课程描述"></el-input>
        </el-form-item>
        <el-form-item label="授课教师" prop="teacherId">
          <el-select v-model="form.teacherId" placeholder="请选择授课教师">
            <el-option v-for="teacher in teachers" :key="teacher.id" :label="teacher.name" :value="teacher.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="学分" prop="credit">
          <el-input-number v-model="form.credit" :min="1" :max="10" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="课程类型" prop="courseType">
          <el-select v-model="form.courseType" placeholder="请选择课程类型" style="width: 100%;">
            <el-option label="直播课" value="live"></el-option>
            <el-option label="录播课" value="recorded"></el-option>
            <el-option label="公共课" value="public"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="form.startDate" type="date" placeholder="选择开始日期" style="width: 100%;"
            value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="form.endDate" type="date" placeholder="选择结束日期" style="width: 100%;"
            value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ editMode ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import courseService from '@/services/courseService';
import { List, Search } from '@element-plus/icons-vue';
import * as echarts from 'echarts';

const courses = ref([]);
const teachers = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const editMode = ref(false);
const formRef = ref(null);

const searchCourseName = ref('');
const isCardView = ref(true); // New: State for view toggle, default to card view

// ECharts refs
const courseTypeDistributionChart = ref(null);
const courseProgressDistributionChart = ref(null);
const creditDistributionChart = ref(null);

let myCourseTypeDistributionChart = null;
let myCourseProgressDistributionChart = null;
let myCreditDistributionChart = null;

const form = ref({
  id: null,
  name: '',
  description: '',
  teacherId: null,
  credit: null,
  courseType: '',
  startDate: null,
  endDate: null,
});

const rules = reactive({
  name: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  courseType: [{ required: true, message: '请选择课程类型', trigger: 'change' }],
  teacherId: [{ required: true, message: '请选择授课教师', trigger: 'change' }],
  credit: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    { type: 'number', message: '学分必须是数字', trigger: 'blur', transform: (value) => Number(value) }
  ],
  description: [{ required: true, message: '请输入课程描述', trigger: 'blur' }],
  startDate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  endDate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
});

const typeMap = {
  live: '直播课',
  recorded: '录播课',
  public: '公共课',
};

const parseProgress = (startDateStr, endDateStr) => {
  if (!startDateStr || !endDateStr) {
    return '日期未设置';
  }

  const startDate = new Date(startDateStr);
  const endDate = new Date(endDateStr);
  const currentDate = new Date();

  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {
    return '日期格式错误';
  }

  if (startDate > endDate) {
    return '日期无效';
  }

  const totalDuration = endDate.getTime() - startDate.getTime();
  const elapsedDuration = currentDate.getTime() - startDate.getTime();

  if (totalDuration <= 0) {
    if (currentDate >= endDate) {
      return '100%';
    } else {
      return '0%';
    }
  }

  let percentage = (elapsedDuration / totalDuration) * 100;

  if (percentage < 0) {
    percentage = 0;
  } else if (percentage > 100) {
    percentage = 100;
  }

  return `${Math.round(percentage)}%`;
};

// Toggle view function
const toggleView = () => {
  isCardView.value = !isCardView.value;
};

const fetchCourses = async () => {
  loading.value = true;
  try {
    const response = await courseService.getCourses();
    courses.value = response.data;
    console.log("获取到的课程列表:", courses.value);
    updateCharts();
  } catch (error) {
    console.error('获取课程列表失败:', error);
    ElMessage.error('获取课程列表失败');
  } finally {
    loading.value = false;
  }
};

const fetchTeachers = async () => {
  try {
    const response = await courseService.getTeachers();
    teachers.value = response.data;
  } catch (error) {
    console.error('获取教师列表失败:', error);
    ElMessage.error('获取教师列表失败');
  }
};

const teacherName = computed(() => (teacherId) => {
  const teacher = teachers.value.find(t => t.id === teacherId);
  return teacher ? teacher.name : '未知教师';
});

const filteredCourses = computed(() => {
  if (!searchCourseName.value) {
    return courses.value;
  }
  const searchTerm = searchCourseName.value.toLowerCase();
  return courses.value.filter(course =>
    course.name.toLowerCase().includes(searchTerm)
  );
});

const filterCourses = () => {
  // filteredCourses computed property handles the filtering automatically
  // This function is just a trigger for @input if needed, but no explicit action is required here.
};

const openAddDialog = () => {
  editMode.value = false;
  dialogVisible.value = true;
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields();
      Object.assign(form.value, {
        id: null,
        name: '',
        description: '',
        teacherId: null,
        credit: null,
        courseType: '',
        startDate: null,
        endDate: null,
      });
    }
  });
};

const openEditDialog = (row) => {
  editMode.value = true;
  dialogVisible.value = true;
  nextTick(() => {
    if (formRef.value) {
      formRef.value.resetFields();
      Object.assign(form.value, {
        ...row,
        startDate: row.startDate || null,
        endDate: row.endDate || null,
      });
    }
  });
};


const handleClose = (done) => {
  ElMessageBox.confirm('确定要关闭吗？未保存的更改将丢失。')
    .then(() => {
      done();
    })
    .catch(() => {
      // User canceled close
    });
};

const submitForm = async () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.value.startDate && form.value.endDate && new Date(form.value.startDate) > new Date(form.value.endDate)) {
          ElMessage.error('结束日期不能早于开始日期');
          return;
        }

        if (editMode.value) {
          await courseService.updateCourse(form.value.id, form.value);
          ElMessage.success('课程更新成功');
        } else {
          await courseService.createCourse(form.value);
          ElMessage.success('课程创建成功');
        }
        dialogVisible.value = false;
        fetchCourses();
      } catch (e) {
        console.error('操作失败:', e);
        ElMessage.error('操作失败: ' + (e.response?.data?.message || e.message || '未知错误'));
      }
    } else {
      ElMessage.error('请检查表单输入');
      return false;
    }
  });
};

const deleteCourse = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除课程 "${row.name}" 吗？此操作将仅删除课程本身！`, '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    console.log("尝试删除课程ID:", row.id);
    const res = await courseService.deleteCourse(row.id);
    if (res.data && res.data.success) {
      ElMessage.success('删除成功');
      fetchCourses();
    } else if (res.data && res.data.message) {
      ElMessage.error('删除失败: ' + res.data.message);
    } else {
      ElMessage.error('删除失败，请稍后重试');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败详情:', error.response ? error.response.data : error.message);
      ElMessage.error('删除失败: ' + (error.response?.data?.message || error.message || '未知错误'));
    }
  }
};

// --- ECharts Logic ---
const CHART_COLORS = [
  '#6a994e', // Deeper Green
  '#c77dff', // Medium Purple
  '#f7b267', // Soft Orange
  '#5c9ead', // Teal
  '#a3a380', // Olive Green
  '#e07a5f', // Terracotta
  '#81b29a', // Sage Green
  '#f2cc8f', // Pale Yellow
  '#b5838d', // Rosy Brown
  '#4a5759', // Dark Slate Gray
];


function initializeCharts() {
  if (courseTypeDistributionChart.value) {
    myCourseTypeDistributionChart = echarts.init(courseTypeDistributionChart.value);
  }
  if (courseProgressDistributionChart.value) {
    myCourseProgressDistributionChart = echarts.init(courseProgressDistributionChart.value);
  }
  if (creditDistributionChart.value) {
    myCreditDistributionChart = echarts.init(creditDistributionChart.value);
  }
  updateCharts();
}

function updateCharts() {
  if (!courses.value.length) {
    myCourseTypeDistributionChart && myCourseTypeDistributionChart.clear();
    myCourseProgressDistributionChart && myCourseProgressDistributionChart.clear();
    myCreditDistributionChart && myCreditDistributionChart.clear();
    return;
  }

  // Course Type Distribution Chart Data (Pie Chart)
  const courseTypeCounts = {};
  courses.value.forEach(course => {
    courseTypeCounts[course.courseType] = (courseTypeCounts[course.courseType] || 0) + 1;
  });
  const courseTypeData = Object.entries(courseTypeCounts).map(([type, count]) => ({
    name: typeMap[type] || type,
    value: count
  }));

  if (myCourseTypeDistributionChart) {
    myCourseTypeDistributionChart.setOption({
      tooltip: { trigger: 'item' },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#666'
        }
      },
      series: [
        {
          name: '课程类型',
          type: 'pie',
          radius: '50%',
          data: courseTypeData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            color: '#333',
            formatter: '{b}: {c} ({d}%)'
          }
        }
      ],
      color: CHART_COLORS
    });
  }

  // Course Progress Distribution Chart Data (Bar Chart)
  const progressRanges = {
    '0%': 0,
    '1%-20%': 0,
    '21%-40%': 0,
    '41%-60%': 0,
    '61%-80%': 0,
    '81%-99%': 0,
    '100%': 0
  };

  courses.value.forEach(course => {
    const progressStr = parseProgress(course.startDate, course.endDate);
    const progressNum = parseFloat(progressStr.replace('%', ''));

    if (progressNum === 0) {
      progressRanges['0%']++;
    } else if (progressNum > 0 && progressNum <= 20) {
      progressRanges['1%-20%']++;
    } else if (progressNum > 20 && progressNum <= 40) {
      progressRanges['21%-40%']++;
    } else if (progressNum > 40 && progressNum <= 60) {
      progressRanges['41%-60%']++;
    } else if (progressNum > 60 && progressNum <= 80) {
      progressRanges['61%-80%']++;
    } else if (progressNum > 80 && progressNum < 100) {
      progressRanges['81%-99%']++;
    } else if (progressNum === 100) {
      progressRanges['100%']++;
    }
  });

  const progressCategories = Object.keys(progressRanges);
  const progressSeriesData = Object.values(progressRanges);

  if (myCourseProgressDistributionChart) {
    myCourseProgressDistributionChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: progressCategories,
        axisLabel: {
          color: '#666',
          interval: 0,
          rotate: 30
        }
      },
      yAxis: {
        type: 'value',
        name: '课程数量',
        axisLabel: {
          color: '#666'
        }
      },
      series: [
        {
          name: '课程数量',
          type: 'bar',
          data: progressSeriesData,
          itemStyle: {
            color: CHART_COLORS[0]
          },
          label: {
            show: true,
            position: 'top',
            color: '#333'
          }
        }
      ],
      color: CHART_COLORS
    });
  }

  // Credit Distribution Chart Data (Pie Chart)
  const creditCounts = {};
  courses.value.forEach(course => {
    if (course.credit !== null) {
      const creditKey = String(course.credit);
      creditCounts[creditKey] = (creditCounts[creditKey] || 0) + 1;
    }
  });

  const creditData = Object.entries(creditCounts).map(([credit, count]) => ({
    name: `${credit} 学分`,
    value: count
  }));

  if (myCreditDistributionChart) {
    myCreditDistributionChart.setOption({
      tooltip: { trigger: 'item' },
      legend: {
        orient: 'vertical',
        left: 'left',
        textStyle: {
          color: '#666'
        }
      },
      series: [
        {
          name: '学分分布',
          type: 'pie',
          radius: '50%',
          data: creditData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          label: {
            color: '#333',
            formatter: '{b}: {c} ({d}%)'
          }
        }
      ],
      color: CHART_COLORS
    });
  }
}

watch(courses, () => {
  if (courses.value.length > 0) {
    updateCharts();
  } else {
    myCourseTypeDistributionChart && myCourseTypeDistributionChart.clear();
    myCourseProgressDistributionChart && myCourseProgressDistributionChart.clear();
    myCreditDistributionChart && myCreditDistributionChart.clear();
  }
}, { deep: true });


onMounted(async () => {
  await fetchTeachers();
  await fetchCourses();

  initializeCharts();

  window.addEventListener('resize', () => {
    myCourseTypeDistributionChart && myCourseTypeDistributionChart.resize();
    myCourseProgressDistributionChart && myCourseProgressDistributionChart.resize();
    myCreditDistributionChart && myCreditDistributionChart.resize();
  });
});

</script>

<style scoped>
.dashboard-card {
  margin: 20px;
  background-color: #f8f8f8;
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.card-header .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.header-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.chart-section {
  margin-top: 25px;
  margin-bottom: 25px;
}

.chart-card {
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  border-radius: 8px;
  background-color: #ffffff;
  transition: transform 0.3s ease-in-out;
}

.chart-card:hover {
  transform: translateY(-3px);
}

.chart-card h3 {
  text-align: center;
  margin-bottom: 20px;
  color: #4a4a4a;
  font-size: 17px;
  padding-top: 15px;
}

/* Table styling */
.el-table {
  margin-top: 20px;
  border-radius: 8px;
  overflow: hidden;
}

.el-table__header-wrapper th {
  background-color: #eef2f5;
  color: #555;
  font-weight: bold;
}

/* Adjusted styles for Course Cards to match the screenshot */
.course-card-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 30px;
  margin-top: 20px;
  padding-bottom: 20px;
  justify-content: flex-start;
}

.course-card {
  /* 确保这里没有 width: 180px; 或者任何固定的 width */
  /* 让它根据 el-col 的分配自动填充宽度 */
  min-height: 220px; /* Ensure a minimum height for consistency */
  border-radius: 8px; /* Slightly more rectangular */
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08); /* Lighter shadow for a more "flat" look */
  transition: all 0.2s ease;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: #ffffff;
  border: 1px solid #e9e9e9; /* Very subtle border */
}

.course-card:hover {
  transform: translateY(-2px); /* Subtle lift on hover */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* Slightly deeper shadow on hover */
}

.course-card-content {
  padding: 12px; /* Reduced padding */
  flex-grow: 1;
  display: flex; /* Use flex for content to stack */
  flex-direction: column;
  gap: 4px; /* Small gap between info lines */
}

.course-card-title {
  font-size: 1em; /* Smaller title font */
  font-weight: bold;
  color: #333;
  margin-bottom: 8px; /* Reduced space below title */
  white-space: normal; /* Allow title to wrap */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* Limit title to 2 lines */
  -webkit-box-orient: vertical;
  line-height: 1.4;
  height: 2.8em; /* Fixed height for two lines of text */
}

.course-card-info {
  font-size: 0.85em; /* Smaller info text */
  color: #666;
  margin-bottom: 0; /* Remove bottom margin, rely on gap */
  line-height: 1.4;
}

.course-card-info .info-label {
  font-weight: 500; /* Lighter font weight for labels */
  color: #444;
  margin-right: 5px;
}

.course-card-actions {
  padding: 8px 12px; /* Very small padding for action area */
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end; /* Align buttons to the right as in screenshot */
  gap: 5px; /* Very small gap between buttons */
  background-color: #fafafa;
}

.course-card-actions .el-button {
  min-width: unset; /* Allow buttons to shrink */
  padding: 6px 10px; /* Smaller button padding */
  font-size: 0.85em; /* Smaller button text */
}

.empty-courses {
  width: 100%; /* Ensure empty message spans full width */
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
}


/* Gradient button for toggle view and New Course button */
.gradient-blue-toggle-button {
  color: #fff !important;
  background-image: linear-gradient(to right, #3f51b5, #2196f3) !important;
  border-color: #3f51b5 !important;
  transition: all 0.3s ease;
}

.gradient-blue-toggle-button:hover,
.gradient-blue-toggle-button:focus {
  background-image: linear-gradient(to right, #5c6bc0, #42a5f5) !important;
  border-color: #5c6bc0 !important;
  opacity: 0.9;
  transform: translateY(-2px); /* 添加上浮效果 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
}

.gradient-blue-toggle-button:active {
  background-image: linear-gradient(to right, #303f9f, #1976d2) !important;
  border-color: #303f9f !important;
}

/* Custom light red button style */
.light-red-button {
  background-color: #FEE2E2 !important; /* Light red background */
  color: #EF4444 !important; /* Slightly darker red text */
  border-color: #FEE2E2 !important; /* Light red border */
}

.light-red-button:hover,
.light-red-button:focus {
  background-color: #FECDCD !important; /* Slightly darker light red on hover */
  border-color: #FECDCD !important;
}

.light-red-button:active {
  background-color: #FBB0B0 !important; /* Even darker light red on active */
  border-color: #FBB0B0 !important;
}
</style>